﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using System.IO.Ports;
using System.IO.Ports;

namespace TestRS232Scanner
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        //BackgroundWorker bw;
        //SerialPortReader spr;
        SerialPort serial;
        
        char[] tab;
        char[] tab1;
        private delegate void SetStatementDeleg(string statement);

        public MainWindow()
        {
            InitializeComponent();
        }
        /*
        private void Scanner()
        {
            try
            {
                bw.RunWorkerAsync();
            }
            catch (Exception ex)
            {

            }
        }
         */ 

        private void Window_Loaded_1(object sender, RoutedEventArgs e)
        {            
            //bw = new BackgroundWorker();
            //spr = new SerialPortReader();
            //bw.DoWork += bw_DoWork;
            //Scanner();
            tab = new char[18];
            tab[0] = (char)48;
            tab[1] = (char)48;
            tab[2] = (char)48;
            tab[3] = (char)49;//1                
            tab[4] = (char)59;//;

            tab[5] = (char)27;//ESC
            tab[6] = (char)91;//[
            tab[7] = (char)54;//0
            tab[8] = (char)113;//q

            tab[9] = (char)27;//ESC
            tab[10] = (char)91;//[
            tab[11] = (char)53;//0
            tab[12] = (char)113;//q

            tab[13] = (char)27;//ESC
            tab[14] = (char)91;//[
            tab[15] = (char)55;//0
            tab[16] = (char)113;//q

            tab[17] = (char)13;//CR

            tab1 = new char[10];
            tab1[0] = (char)48;
            tab1[1] = (char)48;
            tab1[2] = (char)48;
            tab1[3] = (char)49;
            tab1[4] = (char)59;//;

            tab1[5] = (char)27;//ESC
            tab1[6] = (char)91;//[
            tab1[7] = (char)49;//0
            tab1[8] = (char)113;//q
            tab1[9] = (char)13;//CR
            RS232Reader();
        }
               
        /*
        void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            value=string.Empty;
            while (true)
            {
                Thread.Sleep(100);   
                try
                {
                    Dispatcher.BeginInvoke(DispatcherPriority.Input, new ThreadStart(() =>
                    {
                        value = spr.Read();
                        if(value!=string.Empty)
                            listBox.Items.Add(value);
                    }));
                }
                catch (Exception ex)
                {
                    
                }
            }
        }
         */
        private void RS232Reader()
        {
            try
            {
                //serialPort = new Model.SerialPort();
                serial = new SerialPort();
                serial.PortName = "COM1";// serialPort.GetPortName(ConfigurationManager.AppSettings["PortName"]);
                serial.BaudRate = 9600; //serialPort.GetBaudRate(ConfigurationManager.AppSettings["BaudRate"]);
                serial.Parity = Parity.None;// serialPort.GetParity(ConfigurationManager.AppSettings["Parity"]);
                serial.StopBits = StopBits.One ;//serialPort.StopBits(ConfigurationManager.AppSettings["StopBits"]);
                serial.DataBits = 8; ;//serialPort.GetDataBits(ConfigurationManager.AppSettings["DataBits"]);
                serial.DataReceived += serial_DataReceived;
                serial.ErrorReceived += serial_ErrorReceived;
                //serial.ReadTimeout = 500;
                //serial.WriteTimeout = 500;

                if(!serial.IsOpen)
                    serial.Open();
            }
            catch (Exception ex)
            {
                //DAL.Logger.WriteException(ex);
                MessageBox.Show(ex.Message);
            }
        }

        void serial_ErrorReceived(object sender, System.IO.Ports.SerialErrorReceivedEventArgs e)
        {
            Dispatcher.BeginInvoke(new SetStatementDeleg(Visualiser), new object[] { e.ToString() });
        }

        void serial_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            //Thread.Sleep(50);
            //serial.DiscardOutBuffer();
            //serial.DiscardInBuffer();
            
            try
            {
                var str = serial.ReadLine().TrimEnd('\r').Split(';');
                string value = string.Empty;
                //serial.DiscardOutBuffer();
                if (str[str.Length-1].ToString().Equals("L0001"))
                {
                    var x = "0001;"+(char)27+"[3q"+(char)13;
                    serial.Write(x);
                }
                else
                {
                    var x = "0001;" + (char)27 + "[0q" + (char)13;
                    serial.Write(new string(tab1));                    
                }

                //serial.DiscardOutBuffer();
                //serial.DiscardInBuffer();
                value = string.Format("{0}/{1}", serial.ReadBufferSize, serial.WriteBufferSize);
                Dispatcher.BeginInvoke(new SetStatementDeleg(Visualiser), new object[] { value });
            }
            catch (Exception ex)
            {
                //DAL.Logger.WriteException(ex);
                Dispatcher.BeginInvoke(new SetStatementDeleg(Visualiser), new object[] { ex.Message });
            }
        }

        private void Visualiser(string _value)
        {
            try
            {
                listBox.Items.Add(_value);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void MainWindow_Closing_1(object sender, CancelEventArgs e)
        {
            try
            {
                if (serial.IsOpen)
                    serial.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        private void Button_Click_1(object sender, RoutedEventArgs e)
        {
            if (serial.IsOpen)
            {
                
            }
        }
    }
}
